package com.blog.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTime {
	/**
	 * 获取电脑当前时间
	 * @return
	 */
	public static Timestamp getDateTime() {
		Calendar calendar= Calendar.getInstance();
//		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());
		return timestamp;
	}
	
	
	/**
	 * 传入一个Timestamp startTime的时间参数和要增加的天数，返回增加后的天数
	 * @param startTime
	 * @param day
	 * @return
	 */
	public static Timestamp addTimeByDays(Timestamp startTime ,int day) {
	    Calendar endCal = Calendar.getInstance();
	    endCal.setTimeInMillis(startTime.getTime());
	    endCal.add(Calendar.DAY_OF_YEAR, day);
	    Timestamp time =new Timestamp(endCal.getTimeInMillis());
		return time;
	}
	/**
	* 字符串转换成日期
	* @param str
	* @return date
	*/
	public static Timestamp StrToDate(String str) {
//		str+=" 00:00:00";
		Timestamp timestamp = null;
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//或者修改为 yyyy-MM-dd
	    Date date = null;
	    try {
	        date = format.parse(str);
	        timestamp = new Timestamp(date.getTime());
	    } catch (ParseException e) {
	        e.printStackTrace();
	    }
	    return timestamp;
	}
	
	
	public static int betweenDays(Timestamp startCal , Timestamp endCal ) {
		return Math.abs((int)(startCal.getTime() - endCal.getTime())/(1000*60*60*24));
	}
	
	 public static void main(String[] args) {
		 //测试addTimeByDays方法
		long tmpTime = System.currentTimeMillis();
	    Timestamp time = new Timestamp(tmpTime);
	    time.toString();
	    System.out.println(DateTime.addTimeByDays(time, 30));
	    
	    System.out.println(DateTime.addTimeByDays(StrToDate("2017-12-30 00:02:00"), 520));
	    
	    String t1 = "2018-10-20";
	    String t2 = "2018-11-20 04:23:00";
	    
	    String strDate="2005-04-22";
	    
        //注意：SimpleDateFormat构造函数的样式与strDate的样式必须相符
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //加上时间
        //必须捕获异常
        try {
            Date date=simpleDateFormat.parse(t1);
            System.out.println(date);
            
            date = sDateFormat.parse(t2);
            System.out.println(date);
            
        } catch(ParseException px) {
            px.printStackTrace();
        }
        
        System.out.println(StrToDate(t2));
        
        Timestamp startCal = getDateTime();
        Timestamp endCal = addTimeByDays(getDateTime(),20);
		
		long between2 = (startCal.getTime() - endCal.getTime())/(1000*60*60*24);
		System.out.println(betweenDays(startCal,endCal));
		

	}
		
}
